﻿namespace WebMarkupMin.Example.Mvc.Controllers
{
	using System.Web.Mvc;

	using AutoMapper;

	using Core.Minifiers;
	using Core.Settings;
	using ViewModels;
	using ViewModels.Settings;
	using WebMarkupMin.Mvc.ActionFilters;

    public class XmlMinifierController : Controller
    {
		[HttpGet]
		[CompressContent]
		[MinifyXhtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
		public ActionResult Index()
		{
			var model = InitModel();

			return View(model);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Index(FormCollection collection)
		{
			var model = InitModel();

			TryUpdateModel(model, new[] { "SourceCode", "Settings" }, collection);

			if (ModelState.IsValid)
			{
				var settings = Mapper.Map<XmlMinificationSettings>(model.Settings);

				var xmlMinifier = new XmlMinifier(settings);
				var result = xmlMinifier.Minify(model.SourceCode, true);

				model.Result = Mapper.Map<MarkupMinificationResultViewModel>(result);

				ModelState.Clear();
			}

			return View(model);
		}

	    [NonAction]
	    private XmlMinificationViewModel InitModel()
	    {
		    var settings = Mapper.Map<XmlMinificationSettingsViewModel>(new XmlMinificationSettings());
			var model = new XmlMinificationViewModel
			{
				SourceCode = string.Empty,
				Settings = settings,
				Result = null
			};

		    return model;
	    }
    }
}